package com.ruoyi.web.sso.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RsaUtils;
import com.ruoyi.web.sso.common.util.*;
import com.ruoyi.web.sso.common.util.ErrorCode;
import com.ruoyi.web.sso.domain.*;
import com.ruoyi.web.sso.domain.DTO.*;
import com.ruoyi.web.sso.domain.vo.*;
import com.ruoyi.web.sso.mapper.*;
import com.ruoyi.web.sso.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.PrivateKey;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author cdd
 * @since 2021-10-20
 */
@Service
@Slf4j
public class StaffServiceImpl implements IStaffService {


    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private AreaStaffMapper areaStaffMapper;

    @Autowired
    private IRedisUtilService redisService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PlatformMapper platformMapper;

    @Autowired
    private LoginRecordMapper loginRecordMapper;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private StaffRoleMapper staffRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private IDictDataService dictDataService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IAreaStaffService areaStaffService;

    @Autowired
    private  GroupUserMapper groupUserMapper;

    @Autowired
    private  GroupMapper groupMapper;

    @Autowired
    private  StaffChildMapper staffChildMapper;

    @Value("${private.key}")
    private String privateKeys;

    @Override
    public AjaxResult create(CreateStaff createStaff) {
        Staff staff = staffMapper.mobileStaff(createStaff.getMobile());
        if (AssertUtil.isEmpty(staff)) {
//            // 校验密码复杂度
//            if (!isValidPassword(createStaff.getPassword())) {
//                return AjaxResult.error("密码需包含大小写、数字、特殊字符中的至少2种，且长度≥8位");
//            }

            staff = new Staff();
            BeanUtils.copyProperties(createStaff, staff);
            staff.setId(UuidUtil.getUuid());
            staff.setLogName(createStaff.getMobile());
            staff.setRaw(PasswordUtil.createOrderNo());
            staff.setPassword(PasswordUtil.encode(createStaff.getMobile() + createStaff.getPassword() + staff.getRaw()));
            staff.setLastLogin(new Date().getTime());
            staffMapper.insertStaff(staff);
            return AjaxResult.success("账号创建成功！");
        } else {
            return AjaxResult.error("账号已存在！");
        }
    }

    /**
     * 校验密码复杂度：至少8位，且包含大小写、数字、特殊字符中的至少2种组合
     */
    private boolean isValidPassword(String password) {
        if (password == null || password.length() < 8) {
            return false;
        }

        int strength = 0;
        if (password.matches(".*[A-Z].*")) strength++; // 大写字母
        if (password.matches(".*[a-z].*")) strength++; // 小写字母
        if (password.matches(".*\\d.*")) strength++;   // 数字
        if (password.matches(".*[^A-Za-z\\d].*")) strength++; // 特殊字符

        return strength >= 3; // 至少满足3种组合
    }


    @Override
    @Transactional
    public StatusResponse login(Login login, HttpServletRequest req) {
        String headerNames = req.getHeader("ticket");
        //redis 存放对象
        RedisDetails redisDetails = new RedisDetails();
        Staff staff1;
        if (StringUtils.equals(headerNames, "")) {
            Platform platform = platformMapper.selectPlatformByPlatformId(login.getPlatformId());
            if (AssertUtil.isEmpty(platform)) {
                return StatusResponse.error(ErrorCode.SESSION_TOKEN_ERROR, "系统不存在！");
            }
            staff1 = staffMapper.mobileByStaff(login.getMobile());

            if (AssertUtil.isEmpty(staff1)) {
                return StatusResponse.error(ErrorCode.STAFF_NOT_EXIST, "账号不存在！");
            }
            if (!StringUtils.equals(staff1.getPassword(), PasswordUtil.encode(staff1.getMobile() + login.getPassword() + staff1.getRaw()))) {
                return StatusResponse.error(ErrorCode.PASSWORD_ERROR, "密码或账号错误！");
            }
            AreaStaff areaStaff =  areaStaffMapper.getStaffArea(staff1.getAreaId(),staff1.getId());
            if (AssertUtil.isEmpty(areaStaff)){
                return StatusResponse.error(ErrorCode.SESSION_TOKEN_ERROR, "园区关系不存在！");
            }
            if (areaStaff.getStatus() == 1) {
                return StatusResponse.error(ErrorCode.STAFF_NOT_EXIST, "账号已离职，请联系园区管理员！");
            }
            //赋值redis ID
            redisDetails.setStaffId(staff1.getId());
            redisDetails.setPlatformId(login.getPlatformId());

        } else {
            redisDetails = redisService.getTicket(headerNames);

            if (AssertUtil.isEmpty(redisDetails)) {
                return StatusResponse.error("500", "登录过期！");
            }


            staff1 = staffMapper.selectStaffById(redisDetails.getStaffId());
            login.setMobile(staff1.getMobile());
            login.setPlatformId(redisDetails.getPlatformId());
        }

        LoginRecord sosLoginRecord = new LoginRecord();
        sosLoginRecord.setId(UuidUtil.getUuid());
        sosLoginRecord.setStaffId(staff1.getId());
        sosLoginRecord.setPlatformId(login.getPlatformId());
        sosLoginRecord.setLastLogin(new Date().getTime());
        try {
            sosLoginRecord.setLoginIp(String.valueOf(InetAddress.getLocalHost()));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //删除上次信息
        redisService.deleteTicket(redisDetails.getStaffId(), redisDetails.getPlatformId());
        staff1.setLastLogin(new Date().getTime());
        staffMapper.updateStaff(staff1);
        //赋值新缓存
        String ticket = redisService.setTicket(redisDetails.getStaffId(), redisDetails.getPlatformId());

//        //新的 ticket
//        staffDetails.setTicket(ticket);

        //添加登陆记录
        loginRecordMapper.insertLoginRecord(sosLoginRecord);

        return StatusResponse.success(ticket);
    }


    @Override
    public List<Staff> selectAllocatedList(AllocatedStaff allocatedStaff) {
        Map<String, Object> map = JSONObject.parseObject(JSON.toJSONString(allocatedStaff));
        List<Staff> lists = staffMapper.selectAllocatedList(map);
        return lists;
    }


    /**
     * 查询用户信息
     *
     * @param id 用户信息主键
     * @return 用户信息
     */
    @Override
    public Staff selectStaffById(String id) {
        return staffMapper.selectStaffById(id);
    }

    /**
     * 查询用户信息列表
     *
     * @param staff 用户信息
     * @return 用户信息
     */
    @Override
    public List<Staff> selectStaffList(Staff staff) {
        return staffMapper.selectStaffList(staff);
    }

    /**
     * 新增用户信息
     *
     * @param staff 用户信息
     * @return 结果
     */
    @Override
    public int insertStaff(Staff staff) {
        staff.setCreateTime(DateUtils.getNowDate());
        return staffMapper.insertStaff(staff);
    }

    /**
     * 修改用户信息
     *
     * @param staff 用户信息
     * @return 结果
     */
    @Override
    public int updateStaff(Staff staff) {
        Staff staff1 = staffMapper.selectMobileByStaff(staff.getMobile());
        if (AssertUtil.isNotEmpty(staff1) && !StringUtils.equals(staff.getMobile(), staff1.getMobile())) {
            return 1;
        }
        if (!StringUtils.equals(staff.getLogName(),staff.getMobile())){
            staff.setLogName(staff.getMobile());
        }
        AreaStaff areaStaff = new AreaStaff();
        areaStaff.setAreaId(staff.getAreaId());
        areaStaff.setStaffId(staff.getId());
        List<AreaStaff>  areaStaffList = areaStaffService.selectAreaStaffList(areaStaff);
        if (areaStaffList.size()>0){
            areaStaff.setRoleId(areaStaffList.get(0).getRoleId());
            areaStaff.setStatus(Math.toIntExact(staff.getStatus()));
            areaStaffService.updateAreaStaff(areaStaff);
        }
        return staffMapper.updateStaff(staff);
    }

    /**
     * 修改用户信息
     *
     * @param staff 用户信息
     * @return 结果
     */
    @Override
    public int updateStaff2(Staff staff,String paramJson) {
        JSONObject jsonObject = JSONObject.parseObject(paramJson);
        Staff staff1 = staffMapper.selectMobileByStaff(staff.getMobile());
        if (AssertUtil.isNotEmpty(staff1) && !StringUtils.equals(staff.getMobile(), staff1.getMobile())) {
            return 1;
        }
        if (!StringUtils.equals(staff.getLogName(),staff.getMobile())){
            staff.setLogName(staff.getMobile());
        }

        String[] roles = ComUtil.getString(staff.getRoles());
        if(null!=roles && roles.length>0){
            //先删除园区教师绑定关系
            areaStaffMapper.deleteByStaffId(staff.getId(),staff.getAreaId());

            AreaStaff areaStaff2 = new AreaStaff();
            areaStaff2.setStaffId(staff.getId());
            areaStaff2.setAreaId(staff.getAreaId());
            areaStaff2.setRoleId(roles[0]);
            areaStaffMapper.insertAreaStaff(areaStaff2);

            roleService.setStaffRoleList(staff.getAreaId(), staff.getId(), roles);
        }


        this.setStaff(staff,jsonObject);

        //删除之前的用户的一些拓展信息（教育信息、工作履历等）
        staffChildMapper.deleteByStaffId(staff.getId());
        //重新新增
        this.getJsonArray(jsonObject,staff.getId());


        return staffMapper.updateStaff(staff);
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的用户信息主键
     * @return 结果
     */
    @Override
    public int deleteStaffByIds(String ids) {
        return staffMapper.deleteStaffByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除用户信息信息
     *
     * @param id 用户信息主键
     * @return 结果
     */
    @Override
    public int deleteStaffById(String id) {
        return staffMapper.deleteStaffById(id);
    }

    @Override
    public List<Staff> selectUnallocatedList(Map<String, Object> map) {
        return staffMapper.selectUnallocatedList(map);
    }

    @Override
    public List<Staff> selectAreaUnallocatedList(Map<String, Object> map) {
        return staffMapper.selectAreaUnallocatedList(map);
    }

    @Override
    public AjaxResult changeStatus(Staff staff) {
        Staff staff1 = staffMapper.selectStaffById(staff.getId());
        if (AssertUtil.isEmpty(staff1)) {
            return AjaxResult.error("用户对象不存在");
        }
        staff1.setDeleted(staff.getDeleted());
        staffMapper.updateStaff(staff1);
        return AjaxResult.success("用户状态已变更");
    }

    @Override
    public AjaxResult updatePassword(Staff staff) {
        Staff staff1 = staffMapper.selectStaffById(staff.getId());
        if (AssertUtil.isEmpty(staff1)) {
            return AjaxResult.error("用户对象不存在");
        }
        staff1.setPassword(PasswordUtil.encode(staff1.getMobile() + staff.getPassword() + staff1.getRaw()));
        staffMapper.updateStaff(staff1);
        return AjaxResult.success("用户密码已重置");
    }

    @Override
    public Staff selectMobileByStaff(String mobile) {
        return staffMapper.selectMobileByStaff(mobile);
    }

    @Override
    public List<StaffDTO> getRoleByStaffIds(String[] staffIds) {
        return staffMapper.getRoleByStaffIds(staffIds);
    }

    @Override
    public List<StaffDTO> getListByIds(String[] ids) {
        return staffMapper.getListByIds(ids);
    }

    @Override
    public List<Map<String, Object>> getAllStaffByAreaId(String areaId, String mobile) {
        return staffMapper.getAllStaffByAreaId(areaId, mobile);
    }

    @Override
    public int getAreaStaffCount(String areaId) {
        return staffMapper.getAreaStaffCount(areaId);
    }

    @Override
    public StaffDTO selectStaffByIdSso(String staffId) {
        return staffMapper.selectStaffByIdSso(staffId);
    }

    @Override
    public StaffDTO selectStaffByIdSsoRole(String staffId) {
        StaffDTO staffDTO = staffMapper.selectStaffByIdSso(staffId);
        List<Role> roleList = roleMapper.getRoleList(staffId);
        if (roleList!=null){
            List<String> rolesList = new ArrayList<>();
            roleList.forEach(role -> {
                rolesList.add(role.getRoleName());
            });
            staffDTO.setRolesList(rolesList);
        }
        return staffDTO;
    }

    @Override
    public StaffDTO selectMobileByStaffSso(String mobile) {
        return staffMapper.selectMobileByStaffSso(mobile);
    }

    @Override
    public Map updatePassword(String staffId, String oldPassword, String newPassword) {
        Map map = new HashMap();
        Staff staff = staffMapper.selectStaffById(staffId);
        if (AssertUtil.isEmpty(staff)) {
            return AjaxResult.error("用户不存在");
        }

//        String psw = PasswordUtil.encode(oldPassword).toLowerCase();
        //加盐加密后的旧密码
        String oldPassword1 = PasswordUtil.encode(staff.getMobile() + oldPassword + staff.getRaw());
        if (staff.getPassword().equals(oldPassword1)) {
            String encode = (String) PasswordUtil.md5(newPassword,"",false);
            //新密码
            staff.setPassword(PasswordUtil.encode(staff.getMobile() + encode + staff.getRaw()));
            staffMapper.updateStaff(staff);
            map.put("msg", "修改成功");
            return map;
        } else {
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "密码错误");
        }
    }

    @Override
    public StatusResponse passLogin(String platformId, String mobile, String encryptedPassword, String ip, int isGroup) {
        RedisDetails redisDetails = new RedisDetails();
        Platform platform = platformMapper.selectPlatformByPlatformId(platformId);
        if (AssertUtil.isEmpty(platform)) {
            return StatusResponse.error(ErrorCode.SESSION_TOKEN_ERROR, "系统不存在！");
        }

        // 检查是否被锁定
        String lockKey = "login:lock:" + mobile + ":" + platformId;
        if (redisService.exists(lockKey)) {
            return StatusResponse.error(ErrorCode.LOGIN_LOCKED, "登录失败次数过多，请10分钟后重试！");
        }

        Staff staff = staffMapper.mobileByStaff(mobile);
        if (AssertUtil.isEmpty(staff)) {
            recordLoginFailure(mobile, platformId);
//            return StatusResponse.error(ErrorCode.STAFF_NOT_EXIST, "账号不存在！");
            //2025-6-9 修改
            return StatusResponse.error(ErrorCode.STAFF_NOT_EXIST, "密码或账号错误！");
        }

        if (AssertUtil.isEmpty(staff.getAreaId()) || StringUtils.equals(staff.getAreaId(), "null")) {
            recordLoginFailure(mobile, platformId);
            return StatusResponse.error(ErrorCode.STAFF_NOT_EXIST, "账号园区不存在，联系管理！");
        }


        // 解密前端传来的加密密码
        String password;
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKeyFromBase64(privateKeys);
            password = RsaUtils.decrypt(encryptedPassword, privateKey);
        } catch (Exception e) {
            log.error("密码解密失败", e);
            recordLoginFailure(mobile, platformId);
            return StatusResponse.error(ErrorCode.PASSWORD_ERROR, "密码解密失败");
        }
        String encode = (String) PasswordUtil.md5(password,"",false);

        // 校验密码是否匹配
        String psw = PasswordUtil.encode(staff.getMobile() + encode + staff.getRaw());
        if (!StringUtils.equals(staff.getPassword(), psw)) {
            recordLoginFailure(mobile, platformId);
            return StatusResponse.error(ErrorCode.PASSWORD_ERROR, "密码或账号错误！");
        }

        // 校验园区关系
        AreaStaff areaStaff = areaStaffMapper.getStaffArea(staff.getAreaId(), staff.getId());
        if (AssertUtil.isEmpty(areaStaff)) {
            recordLoginFailure(mobile, platformId);
            return StatusResponse.error(ErrorCode.SESSION_TOKEN_ERROR, "园区关系不存在！");
        }

        if (areaStaff.getStatus() == 1) {
            recordLoginFailure(mobile, platformId);
            return StatusResponse.error(ErrorCode.STAFF_NOT_EXIST, "账号已离职，请联系园区管理员！");
        }

        // 集团用户校验
        if (isGroup == 1) {
            GroupUser groupUser = groupUserMapper.selectGroupUserByUserId(staff.getId());
            if (Objects.isNull(groupUser)) {
                recordLoginFailure(mobile, platformId);
                return StatusResponse.error(ErrorCode.STAFF_NOT_EXIST, "用户非集团用户！");
            }

            Group group = groupMapper.selectGroupById(groupUser.getGroupId());
            if (Objects.isNull(group)) {
                recordLoginFailure(mobile, platformId);
                return StatusResponse.error(ErrorCode.STAFF_NOT_EXIST, "集团ID不存在！");
            }
        }

        // 登录成功，清除失败记录
        String failKey = "login:fail:" + mobile + ":" + platformId;
        redisService.delete(failKey);
        redisService.delete(lockKey);

        // 更新最后登录时间
        staff.setLastLogin(new Date().getTime());
        staffMapper.updateStaff(staff);

        // 赋值 Redis ID
        redisDetails.setStaffId(staff.getId());
        redisDetails.setPlatformId(platformId);

        // 保存登录记录
        LoginRecord sosLoginRecord = new LoginRecord();
        sosLoginRecord.setId(UuidUtil.getUuid());
        sosLoginRecord.setStaffId(staff.getId());
        sosLoginRecord.setPlatformId(platformId);
        sosLoginRecord.setLastLogin(new Date().getTime());
        sosLoginRecord.setLoginIp(ip);

        // 删除旧 ticket
//        redisService.deleteTicket(redisDetails.getStaffId(), redisDetails.getPlatformId());

        // 生成新 ticket
        String ticket = redisService.setTicket(redisDetails.getStaffId(), redisDetails.getPlatformId());
        log.info("-------------------------------登录成功----新ticket：" + ticket + "-----------------------------------------------------");

        return StatusResponse.success(ticket);
    }

    /**
     * 记录登录失败次数，并在达到3次时设置锁定
     */
    private void recordLoginFailure(String mobile, String platformId) {
        String failKey = "login:fail:" + mobile + ":" + platformId;
        String lockKey = "login:lock:" + mobile + ":" + platformId;

        // 原子递增失败次数
        Long failCount = redisService.incr(failKey);

        if (failCount == 1) {
            // 第一次失败时设置 TTL 为 10 分钟（使用 expire 方法）
            redisService.expire(failKey, 10 * 60, TimeUnit.SECONDS);
        }

        if (failCount != null && failCount >= 3) {
            // 设置锁定状态，10 分钟后自动过期（使用 set 方法）
            redisService.set(lockKey, System.currentTimeMillis(), 10 * 60, TimeUnit.SECONDS);
        }
    }


    @Override
    public RoleDTO getStaffRole(RedisDetails redisDetails) {
        Staff staff = staffMapper.selectStaffById(redisDetails.getStaffId());
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.UNDEFINED, "用户不存在");
        }
        if (AssertUtil.isEmpty(staff.getAreaId())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "默认园区不存在");
        }
        RoleDTO ret = staffMapper.getStaffRole(redisDetails.getStaffId(), staff.getAreaId());
        return ret;
    }

    @Override
    public List<RoleDTO> getStaffRoleList(RedisDetails redisDetails) {
        Staff staff = staffMapper.selectStaffById(redisDetails.getStaffId());
        if (AssertUtil.isEmpty(staff.getAreaId())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "默认园区不存在");
        }
        return staffMapper.getStaffRoleList(redisDetails.getStaffId(), staff.getAreaId());
    }

    @Override
    public List<RoleDTO> getStaffRoleList(String staffId, String areaId) {

        return staffMapper.getStaffRoleList(staffId, areaId);
    }

    @Override
    public List<RoleCountDO> getAreaRoles(String areaId, boolean staffCount) {
        List<RoleCountDO> list = staffMapper.getAreaRoles(areaId);
        List<RoleCountDO> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            RoleCountDO roleCountDO =  list.get(i);
            Integer count = staffMapper.getStaffRoleCount(list.get(i).getRoleId());
            roleCountDO.setStaffCount(count);
            list1.add(roleCountDO);
        }
        return list1;
    }

    @Override
    public List<StaffDTO> getAreaStaffByRole(String roleId, Integer pageNum, Integer pageSize) {
        Map map = new HashMap();
        map.put("roleId", roleId);
        map.put("num", pageNum);
        map.put("size", pageSize);
        return staffMapper.getAreaStaffByRole(map);
    }

    @Override
    @Transactional
    public RoleDTO setDefaultRole(RedisDetails redisDetails, String roleId) throws Exception {
        Staff staff = staffMapper.selectStaffById(redisDetails.getStaffId());
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.UNDEFINED, "用户不存在");
        }
        Role role = roleMapper.selectRoleByRoleId(roleId);
        if (AssertUtil.isEmpty(role)) {
            throw new BusinessException(ErrorCode.UNDEFINED, "角色不存在");
        }
        if (!role.getAreaId().equals(staff.getAreaId())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "角色不存在");
        }

        List<AreaStaff> list = areaStaffMapper.selectAreaStaffList(new AreaStaff(staff.getAreaId(), staff.getId()));
        if (list.size() > 0) {
            AreaStaff areaStaff = list.get(0);
            areaStaff.setRoleId(roleId);
            areaStaffMapper.updateAreaStaff(areaStaff);
            //查询是否有关联，无关联时候添加关联
            StaffRole staffRole = staffRoleMapper.selectIsExistence(new StaffRole(staff.getId(), roleId));
            if (AssertUtil.isEmpty(staffRole)) {
                //添加角色关联
                staffRoleMapper.insertStaffRole(new StaffRole(staff.getId(), roleId));
            }
        }
        if (AssertUtil.isEmpty(staff.getAreaId())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "默认园区不存在");
        }

        return staffMapper.getStaffRole(redisDetails.getStaffId(), staff.getAreaId());
    }


    @Override
    public RoleDTO getDefaultRole(RedisDetails redisDetails) {
        Staff staff = staffMapper.selectStaffById(redisDetails.getStaffId());
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.UNDEFINED, "用户不存在");
        }
        if (AssertUtil.isEmpty(staff.getAreaId())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "默认园区不存在");
        }
        return staffMapper.getStaffRole(redisDetails.getStaffId(), staff.getAreaId());
    }

    @Override
    public Boolean sendSms(String mobile) {
        if (AssertUtil.isNotEmpty(staffMapper.selectMobileByStaff(mobile))) {
            return true;
        } else {
            return false;
        }
    }


    @Override
    public AreaDetailDTO getAreaDetailDTO(RedisDetails redisDetails) {
        return areaMapper.getAreaDetailDTO(redisDetails.getStaffId());
    }

    @Override
    public AreaDTO getAreaDTO(RedisDetails redisDetails) {
        return areaMapper.getAreaDTO(redisDetails.getStaffId());
    }

    @Override
    public List<AreaListDTO> getInChargeArea(RedisDetails redisDetails) {
        return areaMapper.getInChargeArea(redisDetails.getStaffId());
    }

    @Override
    @Transactional
    public AreaDTO setDefaultArea(String staffId, String areaId) {
        //查询园区默认角色
        AreaStaff areaStaff = areaStaffMapper.getStaffArea(areaId, staffId);

        if (AssertUtil.isNotEmpty(areaStaff)) {
            //查询用户角色关系
            StaffRole staffRole = staffRoleMapper.getStaffRole(areaStaff.getRoleId(), staffId);
            if (AssertUtil.isEmpty(staffRole) && AssertUtil.isNotEmpty(areaStaff.getRoleId())) {
                throw new BusinessException(ErrorCode.UNDEFINED, "园区还未配置角色！");
            }
        }

        areaStaffService.setAreaDefault(areaId, staffId);

        return areaMapper.getAreaDTO(staffId);
    }

    @Override
    public List<String> getNormalStaffIdByArea(RedisDetails redisDetails, String areaId) {
        return areaStaffMapper.getNormalStaffIdByArea(areaId, redisDetails.getStaffId());
    }

    @Override
    public AreaSettingDTO getAreaSetting(String label, String type, String areaId) {
        return dictDataService.selectKeyAndByAreaIdDictData(label, type, areaId);
    }

    @Override
    public List<AreaSettingDTO> getAllAreaSettings(String areaId, String prefix) {
        return dictDataService.getAllAreaSettings(areaId, prefix);
    }

    @Override
    public List<StaffPageDO> getAreaStaffList(String areaId, String roleId, String realName, Integer status ,
                                              Integer pageNum, Integer pageSize,
                                              String isNotStaffIds,String staffIds) {

        Map m = new HashMap();
        m.put("areaId", areaId);
        m.put("roleId", roleId);
        m.put("status", status);
        m.put("num", pageNum);
        m.put("size", pageSize);
        m.put("realName", realName);
        if (null != isNotStaffIds){
            String isNotStaffIdsString = ComUtil.getString(isNotStaffIds);
            String [] isNotStaffIdArr= isNotStaffIdsString.split(",");
            m.put("isNotStaffIds", isNotStaffIdArr);
        }
        if (null != staffIds){
            String staffIdsString = ComUtil.getString(staffIds);
            String [] staffIdsArr= staffIdsString.split(",");
            m.put("staffIds", staffIdsArr);
        }

        return staffMapper.getAreaStaffList(m);
    }

    @Override
    public Integer getAreaStaffListCount(String areaId, String roleId, String realName,Integer status ,
                                         Integer pageNum, Integer pageSize,
                                         String isNotStaffIds,String staffIds) {
        Map m = new HashMap();
        m.put("areaId", areaId);
        m.put("roleId", roleId);
        m.put("realName", realName);
        m.put("status", status);

        return staffMapper.getAreaStaffListCount(m);
    }

    @Override
    public List<StaffPageDO> getGroupStaffList(String groupId, String areaId, String roleId, String realName, Integer status,
                                               Integer beginIndex, Integer pageSize) {

        Map m = new HashMap();

        m.put("groupId", groupId);
        m.put("areaId", areaId);
        m.put("roleId", roleId);
        m.put("status", status);
        m.put("num", beginIndex);
        m.put("size", pageSize);
        m.put("realName", realName);

        return staffMapper.getGroupStaffList(m);
    }

    public Integer getGroupStaffListCount(String groupId, String areaId, String roleId, String realName,Integer status) {

        Map m = new HashMap();
        m.put("groupId", groupId);
        m.put("areaId", areaId);
        m.put("roleId", roleId);
        m.put("realName", realName);

        return staffMapper.getGroupStaffListCount(m);
    }

    @Override
    public List<StaffDTO> getPermissionStaffDTOList(RedisDetails redisDetails, String permission) {
        return staffMapper.getPermissionStaffDTOList(permission, redisDetails.getPlatformId());
    }

    @Override
    public Boolean checkStaffPermission(RedisDetails redisDetails, String[] permission) {
        Staff staff = staffMapper.selectStaffById(redisDetails.getStaffId());

        List<StaffRole> list = staffRoleMapper.getAreaRoleList(staff.getAreaId(),redisDetails.getStaffId());
        if (AssertUtil.isEmpty(list)) {
            return false;
        }
        for (int i = 0; i < permission.length; i++) {
            for (int j = 0; j < list.size(); j++) {
                List<RoleMenu> list1 = roleMenuMapper.isPerms(list.get(j).getRoleId(), permission[i]);
                if (list1.size() > 0) {
                    return true;
                }
            }
        }
        return false;

    }

    private static Boolean getIsPerms(String perms, List<Map<String, Object>> map) {
        for (int i = 0; i < map.size(); i++) {
            String perms1 = (String) map.get(i).get("perms");
            if (StringUtils.equals(perms1, perms)) {
                return true;
            }
        }
        return false;
    }

    private AreaVO getStaffValidArea(List<AreaListDTO> areaList, StaffDTO staff){
        AreaVO areaVO  = null;
        Optional<AreaListDTO> areaOP = areaList.stream().filter(o->o.getAreaId().equals(staff.getAreaId())).findAny();
        if (areaOP.isPresent()){
            areaVO  = areaMapper.selectAreaById(staff.getAreaId());
        } else if (areaList.size() > 0){
            //默认园区失效
            areaVO  = areaMapper.selectAreaById(areaList.get(0).getAreaId());
        } else {
            throw new BusinessException(ErrorCode.UNDEFINED, "当前账号没有加入任何园区！请联系管理员");
        }
        areaVO.setAreaId(areaVO.getId());
        return areaVO;
    }


    @Override
    public Map getPermissionInfoV2(String staffId, String platformId) {

        StaffDTO staff = staffMapper.selectStaffByIdSso(staffId);

        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.UNDEFINED, "用户不存在");
        }

        //用户系统
        Platform platform = platformMapper.selectPlatformByPlatformId(platformId);
        if (platform == null){
            throw new BusinessException(ErrorCode.UNDEFINED, "非法系统");
        }

        //已分配园区集合
        List<AreaListDTO> areaList = areaMapper.getInChargeArea(staffId);

        //获取员工有效的areaId
        AreaVO areaVO  = getStaffValidArea(areaList, staff);

        //默认园区失效
        if (!areaVO.getId().equals(staff.getAreaId())){
            staff.setAreaId(areaVO.getId());  //fix
            setDefaultArea(staffId, areaVO.getId());
        }

        //查询园区关系-默认角色
        AreaStaff areaStaff = areaStaffMapper.getStaffArea(areaVO.getId(), staffId);

        //用户园区角色集合
        List<RoleDTO> roleList = staffMapper.getStaffRoleList(staffId, staff.getAreaId());

        if (roleList.size() == 0){
            throw new BusinessException(ErrorCode.NOT_ROLE_ERROR, "请联系("+areaVO.getAreaName()+")管理员分配角色");
        }

        //查询默认角色信息
        RoleDTO role = null;
        Optional<RoleDTO> roleOp = roleList.stream().filter(o->o.getId().equals(areaStaff.getRoleId())).findAny();
        if(!roleOp.isPresent()){
            //如果角色被删除
            role = roleList.get(0);
            areaStaff.setRoleId(role.getId());
            areaStaffMapper.updateAreaStaff(areaStaff);
        }else{
            role = roleOp.get();
        }

        //菜单
        List<Menu> menus = staffMapper.getRoleIdAndPlatformId(role.getId(), platformId);
        List<MenuList> menuTrees = MenuUtil.getChildPerms(menus, String.valueOf(0));
        if (menuTrees.size() == 0){
            throw new BusinessException(ErrorCode.NOT_ROLE_ERROR, "用户没有当前平台权限！");
        }

        DictData dict = new DictData("0", staff.getAreaId(), null, "CookbookConfig");

        //TODO: 先检查是否已经有创建好的童帮信息
        //TODO: 若已经存在就不需要重复创建
        //为真时代表不存在
        List<DictData> dataList = dictDataService.selectDictDataList(dict);
        Integer recipes = (dataList != null && dataList.size() > 0) ? 1:0;

        Map<String, Object> map = new HashMap<>();
        //是否有带量食谱
        areaVO.setRecipes(recipes);


        GroupUser groupUser = groupUserMapper.selectGroupUserByGroupId(areaVO.getGroupId(),staffId);
        if (Objects.nonNull(groupUser)){
            map.put("isGroupAdmin", true);
        }else {
            map.put("isGroupAdmin", false);
        }

        map.put("staff", staff);
        //默认角色
        map.put("role", role);
        //默认园区
        map.put("area", areaVO);

        map.put("roles", roleList);
        map.put("menuList", menuTrees);
        map.put("areaList", areaList);
        map.put("platformList", Arrays.asList(platform));

        return map;
    }

    @Override
    public List<Map<String, Object>> staffIdByRoleList(String staffId, String roleName) {
        return roleMapper.staffIdByRoleList(staffId, roleName);
    }

    @Override
    public List<AreaVO> staffIdByAreaList(String staffId, String areaName) {
        return areaMapper.staffIdByAreaList(staffId, areaName);
    }

    @Override
    public List<StaffPageDO> getAreaStaffListByPermission(RedisDetails redisDetails, String permission, Integer pageNum, Integer pageSize) {
        //查询默认角色信息
        StaffDTO staff = staffMapper.selectStaffByIdSso(redisDetails.getStaffId());
        if (AssertUtil.isEmpty(staff.getAreaId())) {
            throw new BusinessException(ErrorCode.NOT_ROLE_ERROR, "用户没有权限");
        }
        Map m = new HashMap();
        m.put("areaId", staff.getAreaId());
        m.put("perms", permission);
        m.put("platformId", redisDetails.getPlatformId());
        m.put("status", 0);
        m.put("num", pageNum);
        m.put("size", pageSize);
        return staffMapper.getAreaStaffListByPermission(m);
    }

    @Override
    @Transactional
    public StaffDTO createStaffDTO(StaffDTO staffDTO) {
        Staff staff = staffMapper.mobileByStaff(staffDTO.getMobile());
        String id = UuidUtil.getUuid();
        staffDTO.setId(id);
        StaffDTO staffDTO1= null;
        if (AssertUtil.isEmpty(staff)) {
            staff = new Staff();
            BeanUtils.copyProperties(staffDTO, staff);
            staff.setId(id);
            staff.setLogName(staffDTO.getMobile());
            staff.setRaw(PasswordUtil.createOrderNo());
            staff.setAreaId(staffDTO.getAreaId());
            String psw = PasswordUtil.encode("Abc@123456").toLowerCase();
            staff.setPassword(PasswordUtil.encode(staffDTO.getMobile() + psw + staff.getRaw()));
            staff.setLastLogin(new Date().getTime());
            staffDTO1 =staffMapper.selectMobileByStaffSso(staffDTO.getMobile());
            if (AssertUtil.isNotEmpty(staffDTO1)) {
                BeanUtils.copyProperties(staffDTO1, staff);
                staff.setAreaId(staffDTO.getAreaId());
                staff.setDeleted(0);
                staffMapper.updateStaff(staff);
                staffDTO1.setAreaId(staffDTO.getAreaId());
            }else {
                staffMapper.insertStaff(staff);
            }
        }


        AreaStaff areaStaff1 = areaStaffMapper.getStaffArea(staffDTO.getAreaId(), staff.getId());
        if (AssertUtil.isNotEmpty(areaStaff1)) {
            if (AssertUtil.isNotEmpty(staffDTO1)){
                return  staffDTO1;
            }
            throw new BusinessException(ErrorCode.NOT_ROLE_ERROR, "用户园区已有关系");
        }

        AreaStaff areaStaff = new AreaStaff();
        areaStaff.setStaffId(staff.getId());
        areaStaff.setAreaId(staffDTO.getAreaId());
        areaStaff.setRoleId(ComUtil.getString(staffDTO.getRoles()[0]));
        areaStaffMapper.insertAreaStaff(areaStaff);

        String[] arr = ComUtil.getString(staffDTO.getRoles());
        if (AssertUtil.isNotEmpty(arr)) {
            roleService.setStaffRoleList(staffDTO.getAreaId(), staff.getId(), arr);
        }
        return staffDTO;
    }


    @Override
    @Transactional
    public StaffDTO createStaffDTO2(StaffDTO staffDTO,String paramJson) {
        JSONObject jsonObject = JSONObject.parseObject(paramJson);

        Staff staff = staffMapper.mobileByStaff(staffDTO.getMobile());
        String id = UuidUtil.getUuid();
        staffDTO.setId(id);
        StaffDTO staffDTO1= null;
        if (AssertUtil.isEmpty(staff)) {
            staff = new Staff();
            BeanUtils.copyProperties(staffDTO, staff);
            staff.setId(id);
            staff.setLogName(staffDTO.getMobile());
            staff.setRaw(PasswordUtil.createOrderNo());
            staff.setAreaId(staffDTO.getAreaId());
            String psw = PasswordUtil.encode("Abc@123456").toLowerCase();
            staff.setPassword(PasswordUtil.encode(staffDTO.getMobile() + psw + staff.getRaw()));
            staff.setLastLogin(new Date().getTime());
            staffDTO1 =staffMapper.selectMobileByStaffSso(staffDTO.getMobile());


            if (AssertUtil.isNotEmpty(staffDTO1)) {
                BeanUtils.copyProperties(staffDTO1, staff);

                //处理paramJson  包含两部分参数：用户新增的一些信息和用户拓展信息
                this.setStaff(staff,jsonObject);

                staff.setAreaId(staffDTO.getAreaId());
                staff.setDeleted(0);
                staffMapper.updateStaff(staff);
                staffDTO1.setAreaId(staffDTO.getAreaId());
            }else {
                //处理paramJson  包含两部分参数：用户新增的一些信息和用户拓展信息
                this.setStaff(staff,jsonObject);
                staffMapper.insertStaff(staff);
            }
        }


        AreaStaff areaStaff1 = areaStaffMapper.getStaffArea(staffDTO.getAreaId(), staff.getId());
        if (AssertUtil.isNotEmpty(areaStaff1)) {
            if (AssertUtil.isNotEmpty(staffDTO1)){
                return  staffDTO1;
            }
            throw new BusinessException(ErrorCode.NOT_ROLE_ERROR, "用户园区已有关系");
        }

        if(null!=staffDTO.getRoles() && staffDTO.getRoles().length>0){
            String[] arr = ComUtil.getString(staffDTO.getRoles());

            AreaStaff areaStaff = new AreaStaff();
            areaStaff.setStaffId(staff.getId());
            areaStaff.setAreaId(staffDTO.getAreaId());
            areaStaff.setRoleId(arr[0]);
            areaStaffMapper.insertAreaStaff(areaStaff);

            roleService.setStaffRoleList(staffDTO.getAreaId(), staff.getId(), staffDTO.getRoles());

        }

        //新增业务逻辑：新增用户时，新增用户的一些拓展信息（教育信息、工作履历等）
        this.getJsonArray(jsonObject,staff.getId());

        return staffDTO;
    }

    public void setStaff(Staff staff,JSONObject jsonObject){
        String realName = jsonObject.getString("realName");//姓名
        Integer gender = jsonObject.getInteger("gender");//性别
        String idCard = jsonObject.getString("idCard");//身份证号
        Date birthTime = jsonObject.getDate("birthTime");//出生日期
        Integer age = jsonObject.getInteger("age");//年龄
        Integer types = jsonObject.getInteger("types");//年龄
        String contactInformation = jsonObject.getString("contactInformation");//联系方式
        String nationality = jsonObject.getString("nationality");//民族
        String homeAddress = jsonObject.getString("homeAddress");//家庭住址
        String currentAddress = jsonObject.getString("currentAddress");//现住住址
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");
        String district = jsonObject.getString("district");
        String detailedAddress = jsonObject.getString("detailedAddress");
        String emergencyName = jsonObject.getString("emergencyName");//紧急联系人
        String emergencyMobile = jsonObject.getString("emergencyMobile");//紧急联系人
        String workFormPhoto = jsonObject.getString("workFormPhoto");//工作形象照
        String certificate = jsonObject.getString("certificate");//学历证书
        String certificateEmployment = jsonObject.getString("certificateEmployment");//从业证书
        Date physicalReportStart = jsonObject.getDate("physicalReportStart");//体检报告开始时间
        Date physicalReportEnd = jsonObject.getDate("physicalReportEnd");//体检报告结束时间
        String physicalReportFile = jsonObject.getString("physicalReportFile");//体检报告
        Date certificateClearanceStart = jsonObject.getDate("certificateClearanceStart");//无犯罪证明开始时间
        Date certificateClearanceEnd = jsonObject.getDate("certificateClearanceEnd");//无犯罪证明结束时间
        String certificateClearanceFile = jsonObject.getString("certificateClearanceFile");//无犯罪证明
        String file = jsonObject.getString("file");//附件
        String introduction = jsonObject.getString("introduction");//简介
        staff.setRealName(realName);
        staff.setGender(gender);
        staff.setIdCard(idCard);
        staff.setBirthTime(birthTime);
        staff.setAge(age);
        staff.setTypes(types);
        staff.setContactInformation(contactInformation);
        staff.setNationality(nationality);
        staff.setHomeAddress(homeAddress);
        staff.setCurrentAddress(currentAddress);
        staff.setProvince(province);
        staff.setCity(city);
        staff.setDistrict(district);
        staff.setDetailedAddress(detailedAddress);
        staff.setEmergencyName(emergencyName);
        staff.setEmergencyMobile(emergencyMobile);
        staff.setWorkFormPhoto(workFormPhoto);
        staff.setCertificate(certificate);
        staff.setFile(file);
        staff.setCertificateEmployment(certificateEmployment);
        staff.setPhysicalReportStart(physicalReportStart);
        staff.setPhysicalReportEnd(physicalReportEnd);
        staff.setPhysicalReportFile(physicalReportFile);
        staff.setCertificateClearanceStart(certificateClearanceStart);
        staff.setCertificateClearanceEnd(certificateClearanceEnd);
        staff.setCertificateClearanceFile(certificateClearanceFile);
        staff.setIntroduction(introduction);

    }

    public void getJsonArray(JSONObject jsonObject,String staffId){

//        JSONArray staffChildPOList6 = jsonObject.getJSONArray("staffChildPOList6");
//        if(null!=staffChildPOList6 && staffChildPOList6.size()>0){
//            for (int i = 0; i < staffChildPOList6.size(); i++) {
//                JSONObject item = staffChildPOList6.getJSONObject(i);
//                Date certificateClearanceStart = item.getDate("certificateClearanceStart");//无犯罪证明开始时间
//                Date certificateClearanceEnd = item.getDate("certificateClearanceEnd");//无犯罪证明结束时间
//                String certificateClearanceFile = item.getString("certificateClearanceFile");//无犯罪证明
//
//                StaffChild staffChild = new StaffChild();
//                staffChild.setCertificateClearanceStart(certificateClearanceStart);
//                staffChild.setCertificateClearanceEnd(certificateClearanceEnd);
//                staffChild.setCertificateClearanceFile(certificateClearanceFile);
//
//
//                staffChild.setStaffId(staffId);
//                staffChild.setId(UuidUtil.getUuid());
//                staffChild.setType(6);
//                staffChild.setCreateUser(staffId);
//                staffChildMapper.insert(staffChild);
//            }
//        }

//        JSONArray staffChildPOList5 = jsonObject.getJSONArray("staffChildPOList5");
//        if(null!=staffChildPOList5 && staffChildPOList5.size()>0){
//            for (int i = 0; i < staffChildPOList5.size(); i++) {
//                JSONObject item = staffChildPOList5.getJSONObject(i);
//                Date physicalReportStart = item.getDate("physicalReportStart");//体检报告开始时间
//                Date physicalReportEnd = item.getDate("physicalReportEnd");//体检报告结束时间
//                String physicalReportFile = item.getString("physicalReportFile");//体检报告
//
//                StaffChild staffChild = new StaffChild();
//                staffChild.setPhysicalReportStart(physicalReportStart);
//                staffChild.setPhysicalReportEnd(physicalReportEnd);
//                staffChild.setPhysicalReportFile(physicalReportFile);
//
//
//                staffChild.setStaffId(staffId);
//                staffChild.setId(UuidUtil.getUuid());
//                staffChild.setType(5);
//                staffChild.setCreateUser(staffId);
//                staffChildMapper.insert(staffChild);
//            }
//        }

        JSONArray staffChildPOList4 = jsonObject.getJSONArray("staffChildPOList4");
        if(null!=staffChildPOList4 && staffChildPOList4.size()>0){
            for (int i = 0; i < staffChildPOList4.size(); i++) {
                JSONObject item = staffChildPOList4.getJSONObject(i);
                String classesId = item.getString("classesId");//班级id
                String positionHeld = item.getString("positionHeld");//担任岗位
                String classesName = item.getString("classesName");//班级
                Integer staffType = item.getInteger("staffType");//人员类型
                


                StaffChild staffChild = new StaffChild();
                staffChild.setClassesId(classesId);
                staffChild.setPositionHeld(positionHeld);
                staffChild.setStaffId(staffId);
                staffChild.setId(UuidUtil.getUuid());
                staffChild.setStaffType(staffType);
                staffChild.setClassesName(classesName);
                staffChild.setType(4);
                staffChild.setCreateUser(staffId);
                staffChildMapper.insert(staffChild);
            }
        }


        JSONArray staffChildPOList3 = jsonObject.getJSONArray("staffChildPOList3");
        if(null!=staffChildPOList3 && staffChildPOList3.size()>0){
            for (int i = 0; i < staffChildPOList3.size(); i++) {
                JSONObject item = staffChildPOList3.getJSONObject(i);
                String almaMater = item.getString("almaMater");//工作单位名称
                Date startTime = item.getDate("startTime");//工作起止时间
                Date stopTime = item.getDate("stopTime");//工作起止时间
                String major = item.getString("major");//过期时间

                StaffChild staffChild = new StaffChild();
                staffChild.setAlmaMater(almaMater);
                staffChild.setStartTime(startTime);
                staffChild.setStopTime(stopTime);
                staffChild.setMajor(major);
                staffChild.setStaffId(staffId);
                staffChild.setId(UuidUtil.getUuid());
                staffChild.setType(3);
                staffChild.setCreateUser(staffId);
                staffChildMapper.insert(staffChild);
            }
        }


        JSONArray staffChildPOList2 = jsonObject.getJSONArray("staffChildPOList2");
        if(null!=staffChildPOList2 && staffChildPOList2.size()>0){
            for (int i = 0; i < staffChildPOList2.size(); i++) {
                JSONObject item = staffChildPOList2.getJSONObject(i);
                Integer workingCertificate = item.getInteger("workingCertificate");//从业证书
                Date certificationTime = item.getDate("certificationTime");//获证时间
                Date expirationTime = item.getDate("expirationTime");//过期时间
                String certificateEmployment = item.getString("certificateEmployment");//从业证书
//            String certificate = item.getString("certificate");//证书

                StaffChild staffChild = new StaffChild();
                staffChild.setWorkingCertificate(workingCertificate);
                staffChild.setCertificationTime(certificationTime);
                staffChild.setExpirationTime(expirationTime);
                staffChild.setCertificateEmployment(certificateEmployment);
//            staffChild.setCertificate(certificate);
                staffChild.setStaffId(staffId);
                staffChild.setId(UuidUtil.getUuid());
                staffChild.setType(2);
                staffChild.setCreateUser(staffId);
                staffChildMapper.insert(staffChild);
            }
        }


        JSONArray staffChildPOList1 = jsonObject.getJSONArray("staffChildPOList1");
        if(null!=staffChildPOList1 && staffChildPOList1.size()>0){
            for (int i = 0; i < staffChildPOList1.size(); i++) {
                JSONObject item = staffChildPOList1.getJSONObject(i);
                String almaMater = item.getString("almaMater");//毕业院校
                String educationalLevel = item.getString("educationalLevel");//学历层次
                String major = item.getString("major");//所学专业
//            String certificate = item.getString("certificate");//学历证书

                StaffChild staffChild = new StaffChild();
                staffChild.setAlmaMater(almaMater);
                staffChild.setEducationalLevel(educationalLevel);
                staffChild.setMajor(major);
//            staffChild.setCertificate(certificate);
                staffChild.setStaffId(staffId);
                staffChild.setId(UuidUtil.getUuid());
                staffChild.setType(1);
                staffChild.setCreateUser(staffId);
                staffChildMapper.insert(staffChild);
            }
        }

    }

    @Override
    public List<AreaDTO> getStaffGroupByAreaList(String staffId) {
        Staff staff = staffMapper.selectStaffById(staffId);
        AreaVO areaVO = areaMapper.selectAreaById(staff.getAreaId());
        if (AssertUtil.isEmpty(areaVO.getGroupId())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "对象不存在");
        }
        return areaMapper.getStaffGroupByAreaList(staffId);
    }

    @Override
    public List<Area> getGroupAll(String staffId) {
        Staff staff = staffMapper.selectStaffById(staffId);
        AreaVO areaVO = areaMapper.selectAreaById(staff.getAreaId());
        if (AssertUtil.isEmpty(areaVO.getGroupId())) {
            throw new BusinessException(ErrorCode.UNDEFINED, "对象不存在");
        }
        return areaMapper.getGroupAll(staffId);
    }

    @Override
    public Map getStaffNameAndAreaName(String staffId, String areaId) {
        Staff staff = staffMapper.selectStaffById(staffId);
        AreaVO areaVO = areaMapper.selectAreaById(areaId);
        Map map = new HashMap();
        map.put("staffName", "");
        map.put("areaName", "");
        if (AssertUtil.isNotEmpty(staff)) {
            map.put("staffName", staff.getRealName());
        }
        if (AssertUtil.isNotEmpty(areaVO)) {
            map.put("areaName", areaVO.getAreaName());
        }
        return map;
    }

    @Override
    public StaffDTO updateStaffJobStatus(String areaId, String staffId,Integer status) {

        Staff staff = staffMapper.selectStaffById(staffId);
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.ROLE_NOT_EXIST, "用户不存在");
        }

        //员工离职
        AreaStaff areaStaff = areaStaffMapper.getStaffArea(areaId, staffId);
        if (!AssertUtil.isEmpty(areaStaff)) {
            areaStaff.setStatus(status);
            areaStaffMapper.updateAreaStaff(areaStaff);
        }

        return staffMapper.selectStaffByIdSso(staffId);
    }

    @Override
    public List<StaffDTO> getStaffDTOList(String areaId) {
        return staffMapper.getStaffDTOList(areaId);
    }

    @Override
    public List<StaffInfoDTO> getStaffInfoList(String areaId, String[] staffIds) {
        return staffMapper.getStaffInfoList(areaId, staffIds);
    }

    @Override
    public List<Staff> selectGroupStaffList(String groupId, String mobile) {
        return staffMapper.selectGroupStaffList(groupId,mobile);
    }

}
